package com.yonyou.ucf.mdf.app.isvdxq.secondpart.service;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PurOut;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PutInStock;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.OrderNoticeMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.EpclistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.StorerecordEntityMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.TaglistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.utils.DateUtil;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EpcpickService {

    @Autowired
    private EpclistService epclistService;
    @Autowired
    private StorerecordService storerecordService;

    @Autowired
    EpclistMapperImpl tempEpclistMapper;

    @Autowired
    StorerecordEntityMapperImpl tempStorerecordEntityMapper;

    @Autowired
    TaglistMapperImpl tempTaglistMapper;

    @Autowired
    OrderNoticeMapperImpl tempOrderNoticeMapper;

    //删除拣货
    @Transactional(rollbackFor = Exception.class)
    public DataResult EpcpickDel(String recordId, String rfidcodeId, String modifier, String tenantid) throws Exception {
        DataResult dataResult = new DataResult(0, "参数异常");
        List<String> ids_rfidList = new ArrayList<>();
        List<String> ids_recordList = new ArrayList<>();
        if (rfidcodeId.length() > 0) {
            String[] strings = rfidcodeId.split(",");
            ids_rfidList.addAll(Arrays.asList(strings));
        }
        if (recordId.length() > 0) {
            String[] strings = recordId.split(",");
            ids_recordList.addAll(Arrays.asList(strings));
        }
        // 如果为空的话增加一个空值
        if (ids_recordList.size() == 0 || ids_rfidList.size() == 0) {
            dataResult = new DataResult(0, "参数错误");
            return dataResult;
        }

        //EPC 批量更新
        tempEpclistMapper.editStatus(ids_rfidList, modifier, String.valueOf(DxqConfig.StatusOk), tenantid);
        //Storerecord
        tempStorerecordEntityMapper.deleteStorerecordByIds(ids_recordList, modifier, tenantid);

        dataResult = new DataResult(1, "删除拣货信息成功");

        return dataResult;
    }

    // Pad拣货
    @Transactional(rollbackFor = Exception.class)
    public DataResult EpcpickSubmit(List<PurOut> purOutList, String tenantid) throws Exception {
        DataResult dataResult = new DataResult(0, "数据异常");
        if (purOutList == null || purOutList.size() == 0) {
            dataResult = new DataResult(0, "提交的数据条数为空!");
            return dataResult;
        }

        String ordertype = purOutList.get(0).getOrdertype();
        String userId = purOutList.get(0).getCreator();//操作人
        String batchNum = MyTool.GenerateBatchnoDXQ(ordertype);//私有批次
        String pickStatus = String.valueOf(DxqConfig.PickOk); //拣货状态
        // EPC 拣货
        List<String> ids_epc = purOutList.stream().map(e -> e.getRfidcodeId()).distinct()
                .collect(Collectors.toList());
        if (ids_epc == null || ids_epc.size() == 0) {
            dataResult = new DataResult(0, "库存数据不存在!");
            return dataResult;
        }
        //获取库存信息
        List<StorerecordEntity> mylist_record = new ArrayList<>();
        List<EpcEntity> list_epcEntity = epclistService.SelectByIds(ids_epc, tenantid);
        for (PurOut item : purOutList) {
            String epcid = item.getRfidcodeId();
            EpcEntity tempEntity = list_epcEntity.stream().filter(it -> it.getId().equals(epcid))
                    .findFirst().orElse(null);
            if (tempEntity == null) {
                dataResult.setMessage("物料不存在");
                return dataResult;
            }
            StorerecordEntity storerecordEntity = StorerecordService.MakeEntityForPick(item, batchNum, tempEntity,
                    pickStatus);
            mylist_record.add(storerecordEntity);
        }

        if (mylist_record.size() > 0) {
            tempStorerecordEntityMapper.insertBatch(mylist_record);
            tempEpclistMapper.editStatusForPick(ids_epc, userId, pickStatus, tenantid);

            dataResult = new DataResult(1, "信息拣货成功");
        }

        return dataResult;
    }

    // Pad发签
    @Transactional(rollbackFor = Exception.class)
    public DataResult BindEpcSubmit(List<RfidCodebind> codeBindList) {
        DataResult dataResult = new DataResult(0, "操作失败");
        if (codeBindList == null || codeBindList.size() == 0) {
            dataResult = new DataResult(0, "提交的数据条数为空!");
            return dataResult;
        }

        RfidCodebind tempEntity = codeBindList.get(0);
        String tenantId = tempEntity.getTenant_id();
        String ordertype = tempEntity.getOrdertype();
        String batchNum = MyTool.GenerateBatchnoDXQ(ordertype);//私有批次
        List<EpcEntity> mylist_epc = new ArrayList<>();
        List<StorerecordEntity> mylist_record = new ArrayList<>();
        for (RfidCodebind CodeBind : codeBindList) {
            EpcEntity epcEntity = EpclistService.MakeEntityForPad(CodeBind);
            epcEntity.setBatch_no(batchNum);
            mylist_epc.add(epcEntity);
            //二期方案 补录信息修改
            StorerecordEntity storerecordEntity = StorerecordService.MakeEntityForPad(CodeBind, batchNum,
                    epcEntity.getId());
            mylist_record.add(storerecordEntity);
        }
        if (mylist_epc.size() > 0 && mylist_record.size() > 0) {
            tempEpclistMapper.insertBatch(mylist_epc);
            tempStorerecordEntityMapper.insertBatch(mylist_record);
        }

        dataResult = new DataResult(1, "信息保存成功");
        dataResult.setData(batchNum);

        return dataResult;
    }

    //解绑标签 到货发签解绑 到货单取消场景
    @Transactional(rollbackFor = Exception.class)
    public DataResult BindEpcDel(String recordId, String rfidcodeId, String modifier, String tenantid,
                                 boolean checkFlag) throws Exception {
        DataResult dataResult = new DataResult(0, "标签删除失败!");
        List<String> ids_rfidList = new ArrayList<>();
        List<String> ids_recordList = new ArrayList<>();
        if (rfidcodeId.length() > 0) {
            String[] strings = rfidcodeId.split(",");
            ids_rfidList.addAll(Arrays.asList(strings));
        }
        if (recordId.length() > 0) {
            String[] strings = recordId.split(",");
            ids_recordList.addAll(Arrays.asList(strings));
        }
        // 如果为空的话增加一个空值
        if (ids_recordList.size() == 0 || ids_rfidList.size() == 0) {
            dataResult = new DataResult(0, "参数错误");
            return dataResult;
        }
        if (checkFlag) {
            StorerecordEntity storeRecord = storerecordService.SelectByEpcIds(ids_recordList, tenantid);
            if (storeRecord != null) {
                dataResult = new DataResult(0, "要删除的物料标签已到货提交,不允许删除！");
                return dataResult;
            }
        }

        if (ids_recordList.size() > 0) {
            List<EpcEntity> epcEntities = tempEpclistMapper.selectByIds(ids_recordList, tenantid);
            if (epcEntities.size() > 0) {
                for (EpcEntity item : epcEntities) {
                    item.setPk_temp("bindepcdel");
                }
                tempEpclistMapper.insertBatchHistory(epcEntities);
            }
            tempEpclistMapper.deleteByIds(ids_rfidList, tenantid);
            tempStorerecordEntityMapper.deleteByIds(ids_recordList, tenantid);
        }
        dataResult = new DataResult(1, "标签删除成功");

        return dataResult;
    }

    /**
     * 手持机推送接口到用友，用友入库回写本地数据
     *
     * @param putInStockList
     * @param epcIds
     * @param recordIds
     * @param tenantId
     * @param batch_no       用友提交成功批次
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult InStockParamsCallback(List<PutInStock> putInStockList, List<String> epcIds,
                                            List<String> recordIds,
                                            String tenantId, String batch_no) throws Exception {
        DataResult dataResult = new DataResult(0, "操作失败");
        if (putInStockList == null || putInStockList.size() == 0) return dataResult;
        List<StorerecordEntity> list_record = new ArrayList<>();

        try {
            String ordertype = putInStockList.get(0).getOrdertype();
            if (recordIds != null && recordIds.size() > 0)
                list_record = storerecordService.selectStorerecordByIds(recordIds, tenantId);
            if (epcIds != null && epcIds.size() > 0)
                list_record = storerecordService.selectStorerecordByEpcIds(epcIds, ordertype, tenantId);
            if (list_record == null || list_record.size() == 0) {
                dataResult = new DataResult(1, "数据入库成功条数为0");
                return dataResult;
            }
            List<String> ids_epc = list_record.stream()
                    .map(it -> it.getRfidcodeId()).distinct().collect(Collectors.toList());
            List<EpcEntity> list_epcs = epclistService.SelectByIds(ids_epc, tenantId);
            List<String> epcs = list_epcs.stream().map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());

            PutInStock tempEntity = putInStockList.get(0);
            String modifier = tempEntity.getModifier();
            String sourceautoid = tempEntity.getSourceautoid();//orderdetailid
            String sourceid = tempEntity.getSourceid(); //orderid
            String source = tempEntity.getSource();
            String firstsource = tempEntity.getFirstsource();
            String firstsourceautoid = tempEntity.getFirstsourceautoid();
            String firstsourceid = tempEntity.getFirstsourceid();
            String upcode = tempEntity.getUpcode();
            String firstupcode = tempEntity.getFirstupcode();

            //生成批次号
            String picicode = MyTool.GenerateBatchnoDXQ(ordertype);
            Map<String, Object> keymap = new HashMap<>();
            List<String> keyList = new ArrayList<>(); //用于区分组
            for (StorerecordEntity item : list_record) {
                List<PutInStock> entityList = putInStockList.stream()
                        .filter(it -> it.getOrderdetailid().equals(item.getOrderdetailid()))
                        .collect(Collectors.toList());
                if (!StringUtils.isEmpty(item.getBatchno())) {
                    entityList = entityList.stream()
                            .filter(it -> it.getBatchno() != null && it.getBatchno().equals(item.getBatchno()))
                            .collect(Collectors.toList());
                }
                // todo 有效期回写验证 正常应该验证到期时间
                if (!StringUtils.isEmpty(item.getInvalidDate())) {
                    Date tempDate = DateUtil.str2Date(item.getInvalidDate());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String productDate = sdf.format(tempDate);
                    entityList = entityList.stream()
                            .filter(it -> it.getInvaliddate() != null && it.getInvaliddate().startsWith(productDate))
                            .collect(Collectors.toList());
                }
                PutInStock itemEntity = entityList.stream().findFirst().orElse(null);
                if (itemEntity == null) {
                    dataResult.setMessage("远程数据批次或有效期过滤异常");
                    return dataResult;
                }
                item.setSource(source);
                item.setFirstsource(firstsource);
                item.setFirstsourceautoid(firstsourceautoid);
                item.setFirstsourceid(firstsourceid);
                item.setUpcode(upcode);
                item.setFirstupcode(firstupcode);
                item.setPoid(itemEntity.getPoid());
                item.setPodetailid(itemEntity.getPodetailid());
                item.setPocode(itemEntity.getPocode());
                item.setModifier(modifier);
                item.setStockUnitId(itemEntity.getStockUnitId());
                item.setStock_unit_id(itemEntity.getStockUnitId());
                item.setBatch_no(batch_no); // 用友提交成功回写批次
                item.setEpc_status(0); //未上架
                if (!StringUtils.isEmpty(itemEntity.getProductDate()))
                    item.setProductDate(itemEntity.getProductDate());
                if (!StringUtils.isEmpty(itemEntity.getInvaliddate()))
                    item.setInvalidDate(itemEntity.getInvaliddate());
                // 关键字分组
                String keyString = String.join("|", item.getProduct_id(), item.getProduct_sku_id()
                        , item.getBatchno(), item.getProductDate());
                if (keyList.indexOf(keyString) == -1) {
                    keyList.add(keyString);
                    List<StorerecordEntity> temp_val = new ArrayList<>();
                    temp_val.add(item);
                    keymap.put(keyString, temp_val);
                } else {
                    List<StorerecordEntity> temp_val = new ArrayList<>();
                    List<StorerecordEntity> temp_obj = (List<StorerecordEntity>) keymap.get(keyString);
                    if (temp_obj != null) {
                        temp_val.addAll(temp_obj);
                    }
                    temp_val.add(item);
                    keymap.put(keyString, temp_val);
                }
            }
            tempStorerecordEntityMapper.instockByEntity(list_record, picicode, modifier, tenantId);
            //分组更新到期时间
            for (String keyString : keyList) {
                String[] arrKey = keyString.split("\\|");
                String proid = arrKey[0];
                String proskuid = arrKey[1];
                String batchno = arrKey[2];
                String protime = arrKey[3];
                List<StorerecordEntity> tempList = (List<StorerecordEntity>) keymap.get(keyString);
                List<String> ids =
                        tempList.stream().map(it -> it.getRfidcodeId()).distinct().collect(Collectors.toList());
                String invaliddate = tempList.get(0).getInvalidDate();
                tempEpclistMapper.updateInvalidDate(ids, invaliddate, modifier, tenantId, batch_no);
            }

            dataResult = new DataResult(1, "数据入库成功");
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }

        return dataResult;

    }

    /**
     * 用友出库回写
     * 支持多次提交
     *
     * @param purOutList
     * @param orderid
     * @param allotbatchno
     * @param tenantid
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult OutStatusCallback(List<PurOut> purOutList, String orderid, String allotbatchno, String tenantid, String userId) throws Exception {
        DataResult dataResult = new DataResult(0, "操作失败");
        if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(allotbatchno)) {
            return dataResult;
        }
        if (purOutList == null || purOutList.size() == 0) return dataResult;
        purOutList = purOutList.stream().filter(it -> it.getId() != null && StringUtils.isNotEmpty(it.getId())).collect(Collectors.toList());
        List<StorerecordEntity> list_record = new ArrayList<>();
        List<String> storerecordIdList = new ArrayList<>();
        List<String> ids_record = purOutList.stream().map(it -> it.getId()).distinct().collect(Collectors.toList());
        if (ids_record.size() > 0) {
            list_record = storerecordService.selectStorerecordByIds(ids_record, tenantid);
            //生成批次号
            String ordertype = purOutList.get(0).getOrdertype();
            String picicode = MyTool.GenerateBatchnoDXQ(ordertype);
            for (StorerecordEntity itemEntity : list_record) {
                PurOut item = purOutList.stream().filter(it->it.getId().equals(itemEntity.getId())).findAny().orElse(null);
                if ( item !=null ) {
                    itemEntity.setBatch_no(allotbatchno);
                    itemEntity.setSource(item.getSource());
                    itemEntity.setSourceid(item.getSourceid());
                    itemEntity.setSourceautoid(item.getSourceautoid());
                    itemEntity.setFirstsource(item.getFirstsource());
                    itemEntity.setFirstsourceid(item.getFirstsourceid());
                    itemEntity.setFirstsourceautoid(item.getFirstsourceautoid());
                    itemEntity.setFirstupcode(item.getFirstupcode());
                    itemEntity.setPoid(item.getPoid());
                    itemEntity.setPodetailid(item.getPodetailid());
                    itemEntity.setPocode(item.getPocode());
                    itemEntity.setModifier(userId);
                    itemEntity.setModify_time(MyTool.GenerateTime("yyyy-MM-dd HH:mm:ss"));
                    storerecordIdList.add(item.getId());
                }
            }
        }
        if (storerecordIdList.size() == 0){
            dataResult.setMessage("参数异常");
            return dataResult;
        }
        // 启动会话
        if (list_record.size() > 0) {
            // 记录软删除
            tempStorerecordEntityMapper.outstockByEntity(list_record, tenantid);
            List<String> epcs = list_record.stream().map(e -> e.getRfidcode())
                    .distinct().collect(Collectors.toList());
            if (epcs.size() > 0) {
                List<EpcEntity> epcEntities = tempEpclistMapper.selectByEpcs(epcs, tenantid);
                if (epcEntities.size() > 0) {
                    for (EpcEntity item : epcEntities) {
                        item.setPk_temp("outback");
                    }
                    tempEpclistMapper.insertBatchHistory(epcEntities);
                }
                // 出库删除
                tempEpclistMapper.deleteByEpcs(epcs, tenantid);
                tempTaglistMapper.deleteByEpcKeys(epcs, tenantid);
            }
        }
        tempOrderNoticeMapper.EditEntityStatusForPick(orderid, DxqConfig.AllotOk, DxqConfig.StatusOk, allotbatchno, DxqConfig.StatusOk, userId, tenantid);

        dataResult = new DataResult(1, "数据发货成功");
        dataResult.setData(storerecordIdList);

        return dataResult;
    }
}
